package logic

import (
	"cart_srv/cart"
	"cart_srv/internal/svc"
	"cart_srv/model/mysql"
	"cart_srv/model/redis"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 购物车添加
func (l *CartAddLogic) CartAdd(in *cart.CartAddRequest) (*cart.CartAddResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Good{}
	err := g.GetGood(int(in.GoodId))
	if err != nil {
		return nil, fmt.Errorf("信息获取失败")
	}
	if g.ID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}
	if g.ID <= 0 {
		return nil, fmt.Errorf("购物车为空")
	}
	stock := redis.SetStock(int(in.UserId))
	if stock < in.Num {
		return nil, fmt.Errorf("库存不足")
	}
	if redis.GetExists(int(in.UserId), int(in.GoodId)) {
		if redis.UpdateNum(int(in.UserId), int(in.GoodId), int(in.Num)) != nil {
			return nil, fmt.Errorf("数据更新失败")
		}
	} else {
		m := map[string]interface{}{
			"user_id":    in.UserId,
			"good_id":    in.GoodId,
			"good_title": g.GoodTitle,
			"good_price": g.GoodPrice,
			"num":        in.Num,
			"checked":    1,
		}
		err = redis.CartAdd(m)
		if err != nil {
			return nil, fmt.Errorf("添加失败")
		}

	}
	return &cart.CartAddResponse{Success: true}, nil
}
